package com.bootcamp.javase2.network.client_server;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * @program: day22NetworkCode
 * @description:
 * @author: Keyu Li
 * @create: 2021-09-16 19:55
 **/

public class Client {
    static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1", 9999);
        OutputStream out = socket.getOutputStream();
        // print menu
        int choice;
        while ((choice = showMenu()) != 0) {
            // 1 从键盘输入当作socket输出流
            if (choice == 1) outputFromKeyBoard(out);
            // 2 从文件输入当作socket输出流
            if (choice == 2) outputFromTxtFile(out);
        }
//        outputFromTxtFile(out);
//        outputFromKeyBoard(out);
        socket.close();
    }

    private static void outputFromTxtFile(OutputStream out) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader("client.txt"));
        String line;
        while ((line = reader.readLine()) != null) {
            out.write(line.getBytes());
            out.write(System.lineSeparator().getBytes());
        }
        reader.close();
    }

    private static void outputFromKeyBoard(OutputStream out) throws IOException {
        System.out.println("停止词：当且仅当末尾为end时候");
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String line;
        // read line and write
        while (!(line = reader.readLine()).endsWith("end")) {
            out.write(line.getBytes());
            out.write(System.lineSeparator().getBytes());
        }
        // close
//        reader.close();
    }

    static int showMenu() {

        System.out.println("--- 客户端选择 ---");
        System.out.println(" 1. 从键盘录入");
        System.out.println(" 2. client.txt");
        System.out.println(" 0. exit");
        System.out.print("please input:  ");
        int choice = -1;
        while (choice == -1) {
            try {
                choice = Integer.parseInt(scanner.nextLine());
            } catch (NumberFormatException e) {
                choice = -1;
            }
        }
        return choice;
    }
}
